package com.wfh.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfh.constant.RedisLuaScriptConstant;
import com.wfh.mapper.ThumbMapper;
import com.wfh.model.dto.thumb.DoThumbRequest;
import com.wfh.model.entity.Thumb;
import com.wfh.model.entity.User;
import com.wfh.model.enums.LuaStatusEnum;
import com.wfh.service.BlogService;
import com.wfh.service.ThumbService;
import com.wfh.service.UserService;
import com.wfh.utils.RedisKeyUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Arrays;

/**
* @author lenovo
* @description 针对表【thumb】的数据库操作Service实现
* @createDate 2025-04-18 17:26:50
*/
@Service("thumbServiceRedis")
@Slf4j
@RequiredArgsConstructor
public class ThumbServiceRedisImpl extends ServiceImpl<ThumbMapper, Thumb>
    implements ThumbService {

    private final UserService userService;

    private final BlogService blogService;

    private final TransactionTemplate transactionTemplate;

    private final RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 点赞
     *
     * @param doThumbRequest
     * @param request
     * @return
     */
    @Override
    public Boolean doThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        if (doThumbRequest == null || doThumbRequest.getBlogId() == null) {
            throw new RuntimeException("请求参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        Long blogId = doThumbRequest.getBlogId();
        String timeSlice = getTimeSlice();
        // Redis Key
        String tempThumbKey = RedisKeyUtil.getTempThumbKey(timeSlice);
        String userThumbKey = RedisKeyUtil.getUserThumbKey(loginUser.getId());
        // 执行lua脚本
        Long res = redisTemplate.execute(RedisLuaScriptConstant.THUMB_SCRPIT,
                Arrays.asList(tempThumbKey, userThumbKey),
                loginUser.getId(),
                blogId);
        // 如果执行结果是-1，就说明用户已经点赞了
        if (LuaStatusEnum.FAIL.getValue() == res){
            throw new RuntimeException("用户已经点赞");
        }
        // 更新成功才执行
        return LuaStatusEnum.SUCCESS.getValue() == res;
    }

    /**
     * 取消点赞
     *
     * @param doThumbRequest
     * @param request
     * @return
     */
    @Override
    public Boolean undoThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        if (doThumbRequest == null || doThumbRequest.getBlogId() == null) {
            throw new RuntimeException("请求参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        Long blogId = doThumbRequest.getBlogId();
        // 计算时间片
        String timeSlice = getTimeSlice();
        // Redis Key
        String tempThumbKey = RedisKeyUtil.getTempThumbKey(timeSlice);
        String userThumbKey = RedisKeyUtil.getUserThumbKey(loginUser.getId());
        // 执行lua脚本
        Long res = redisTemplate.execute(RedisLuaScriptConstant.UNTHUMB_SCRIPT,
                Arrays.asList(tempThumbKey, userThumbKey),
                loginUser.getId(),
                blogId);
        // 根据返回值处理结果
        if (res == LuaStatusEnum.FAIL.getValue()){
            throw new RuntimeException("用户没有点赞");
        }
        return LuaStatusEnum.SUCCESS.getValue() == res;
    }

    /**
     * 是否已经点赞
     * @param blogId
     * @param userId
     * @return
     */
    @Override
    public Boolean hasThumb(Long blogId, Long userId) {
        return redisTemplate.opsForHash().hasKey(RedisKeyUtil.getUserThumbKey(userId), blogId.toString());
    }

    /**
     * 获取到当前时间前最近的整秒数
     * @return
     */
    private String getTimeSlice(){
        DateTime date = DateUtil.date();
        // 获取到当前时间前最近的整秒数
        return DateUtil.format(date, "HH:mm:") + (DateUtil.second(date) / 10) * 10;
    }
}




